package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import tech.aistar.pojo.User;
import tech.aistar.pojo.dao.CommenttRepository;
import tech.aistar.pojo.entity.Commentt;
import tech.aistar.service.UserService;
import tech.aistar.vo.Result;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("ping")
public class CommenttController {
    @Autowired
    private UserService userService;
    @Autowired
    private CommenttRepository commenttRepository;
    @GetMapping("in/{curr}/{limit}")
    private Result insertto(@PathVariable("curr") String curr, @PathVariable("limit") String limit){
        Pageable pageable = PageRequest.of(Integer.parseInt(limit),Integer.parseInt(curr) );
        Page<Commentt> all3 = commenttRepository.findAll(pageable);
        List<Commentt> content = all3.getContent();
        return new Result("200","查询成功",content);
    }
    @GetMapping ("se")
    private Result sest(){
        List<Commentt> all = commenttRepository.findAll(Sort.by(Sort.Order.asc("number")));
        return new Result("200","查询成功",all);
    }

    @PostMapping("inse/{phone}/{now}/{oSize}")
    private Result insertto(@PathVariable("phone")String phone,@PathVariable("now")String now,@PathVariable("oSize")String comment)
    {
        User user=userService.register(phone);
        Commentt comm = new Commentt();
        comm.setCreateTime(now);
        comm.setFromName(user.getUsername());
        comm.setContent(comment);
        comm.setUPhoto(user.getUPhoto());
        comm.setFromUid(String.valueOf(user.getUId()));
        commenttRepository.insert(comm);
        Commentt commentt= new Commentt();
        commentt.setFromName(user.getUsername());

        Optional<Commentt> stuOp1 = commenttRepository.findOne(Example.of(commentt));

        String name= String.valueOf(stuOp1.get());
        System.out.println(name);

        return new Result("200","插入成功",name);
    }
    @PostMapping("del/{id}")
    private Result delto(@PathVariable("id") String id)
    {
        commenttRepository.deleteById(id);
        return new Result("200","删除成功");
    }
    @PostMapping("up/{zNum}/{uid}")
    private Result upde(@PathVariable("zNum") Integer number,@PathVariable("uid") String id)
    {
        Optional<Commentt> op = commenttRepository.findById(id);
        Commentt commentt = op.get();
        commentt.setNumber(number);
        commenttRepository.save(commentt);
        return new Result("200","更新成功");
    }
}
